import { effect, reactive } from "@feng3d/reactivity";
import { WebRTCHelper } from "@feng3d/webrtchelper";
import { client } from "@feng3d/websocketclient";

/**
 * WebRTC data
 */
export const webrtcData: {
    /**
     * 主机名
     */
    readonly hostname: string
    /**
     * 远端用户名
     */
    readonly remoteUsername: string;
} = {

} as any;

var local_video: HTMLVideoElement;
var received_video: HTMLVideoElement;
var hangup_button: HTMLButtonElement;

window.addEventListener("load", () =>
{
    //
    local_video = document.getElementById("local_video") as HTMLVideoElement;
    received_video = document.getElementById("received_video") as HTMLVideoElement;
    hangup_button = document.getElementById("hangup-button") as HTMLButtonElement;
});

effect(() =>
{
    reactive(webrtcData).hostname;

    //
    WebRTCHelper.hostname = webrtcData.hostname;
});

effect(() =>
{
    reactive(client).username;

    //
    WebRTCHelper.localUsername = client.username;
});

WebRTCHelper.sendToServer = (msg) =>
{
    reactive(client).sendData = msg as any;
};

// 获取本地视频
WebRTCHelper.getOrRequestUserMediaStream().then((localMediaStream) =>
{
    local_video.srcObject = localMediaStream;

    window['onVideoBtn'] = () =>
    {
        WebRTCHelper.videoEnabled = !WebRTCHelper.videoEnabled;
    }

    window['onAudioBtn'] = () =>
    {
        WebRTCHelper.audioEnabled = !WebRTCHelper.audioEnabled;
    }
});

// 监听新增 点对点视频 连接
WebRTCHelper.onCreated = (webRTC: WebRTCHelper) =>
{
    window['hangUpCall'] = () =>
    {
        webRTC.hangUpCall();
    }

    /**
     * 关闭视频后回调
     */
    webRTC.onVideoClosed = () =>
    {
        // Disable the hangup button
        hangup_button.disabled = true;
    }

    /**
     * 收到远程媒体流
     */
    webRTC.onReceivedRemoteMediaStream = (remoteMediaStream) =>
    {
        received_video.srcObject = remoteMediaStream;
        hangup_button.disabled = false;
    }

    window['onRemoteVideoBtn'] = () =>
    {
        webRTC.videoEnabled = !webRTC.videoEnabled;
    }

    window['onRemoteAudioBtn'] = () =>
    {
        webRTC.audioEnabled = !webRTC.audioEnabled;
    }
}

// 
effect(() =>
{
    reactive(client).message;

    const message = client.message;
    if (!message) return;

    if (['video-offer', 'video-answer', 'new-ice-candidate', "hang-up"].indexOf(message.type) !== -1)
    {
        // 接收处理远程发来的点对点协议信息
        WebRTCHelper.receivedFromRemote(message as any);
    }
});

effect(() =>
{
    reactive(webrtcData).remoteUsername;

    if (!webrtcData.remoteUsername) return;

    WebRTCHelper.invite(webrtcData.remoteUsername);
});
